from flask import request, jsonify
import subprocess
import base64
import time
import json
import cv2
import os


def task_name_to_type(ori_task_name):
    translation_dict = {
        "区域入侵": "0",
        "越界检测": "0",
        "物体检测": "0",
        "安全帽识别": "0",
        "烟火检测": "0",
        "反光衣检测": "0",
        "人员离岗": "1",
        "对象滞留": "1",
        "违规占道": "1",
        "人员睡岗": "2",
        "接打电话检测": "0",
        "姿势检测": "2",
        "正位停车": "3",
        "区域交叉": "3"
    }

    task_type = translation_dict[ori_task_name]

    return task_type


def task_classify(task_type):
    classify_list = {
        "0": "object_recognition",
        "1": "object_detention",
        "2": "pose",
        "3": "overlap"
    }

    classify = classify_list[task_type]

    return classify


def return_jsonify():
    return jsonify(
        msg="success",
        code=0
    )


def inference():
    jsons = request.json

    inference_json = str(jsons).replace('"', "'")
    inference_json = inference_json.replace(" ", "")
    inference_json = inference_json.replace('True', 'true')
    inference_json = inference_json.replace('False', 'false')

    json_dict = json.loads(jsons)

    task_type = json_dict['task_type']

    inference_mode = str(task_classify(task_type=task_type))

    path = '/mnt/wisdiot_ai/{}.py'.format(inference_mode)

    cmd = "python3 " + path + " --data " + '"' + f"{inference_json}" + '"'

    try:
        subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    return jsonify(
        msg="success",
        code=0
    )


def cam_frame_shot():
    json_output = {}
    jsons = request.json

    cap = cv2.VideoCapture(jsons)
    camera_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
    camera_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
    pic_time = str(time.strftime("%Y-%m-%d_%H-%M-%S",
                                 time.localtime(time.time())))
    temporary_pic_path = r'/mnt/wisdiot_ai/pic_temporary_save/'
    temporary_pic_name = pic_time
    temporary_pic_format = ".jpg"
    temporary_pic_file = "{0}{1}{2}".format(temporary_pic_path,
                                            temporary_pic_name,
                                            temporary_pic_format)

    try:
        if cap.isOpened():
            ret, frame = cap.read()

            if ret:
                cv2.imwrite(temporary_pic_file, frame)

        temporary_pic = open(temporary_pic_file, "rb")
        pic_base64 = str(base64.b64encode(temporary_pic.read()), 'utf-8')
        temporary_pic.close()
        os.remove(temporary_pic_file)

        json_output['base64img'] = pic_base64
        json_output['camera_width'] = camera_width
        json_output['camera_height'] = camera_height

        return jsonify(
            msg="success",
            code=0,
            data=json_output
        )

    except Exception as e:
        print(e)

        return jsonify(
            msg="Server Internal Error",
            code=1
        )

    finally:
        cap.release()
        cv2.destroyAllWindows()


def model_file():
    try:
        jsons = request.json
        model_path = jsons['model_path']
        model_name = jsons['model_name']

        if os.path.exists(model_path + model_name):
            return jsonify(
                msg="success",
                code=0,
                data="yes"
            )

        else:
            return jsonify(
                msg="success",
                code=0,
                data="no"
            )

    except Exception as e:
        return jsonify(
            msg="Server Internal Error-----" + str(e),
            code=1
        )
